/**
 * Electron环境下的fetch封装
 * 使用主进程的net模块来发起网络请求,绕过渲染进程的CORS限制
 */

export async function electronFetch(url: string, options: RequestInit = {}): Promise<Response> {
  // 检查是否在Electron环境中
  if (typeof window !== 'undefined' && window.electronAPI && window.electronAPI.fetch) {
    console.log('[ElectronFetch] 使用Electron net模块:', url)

    try {
      const result = await window.electronAPI.fetch(url, {
        method: options.method || 'GET',
        headers: options.headers,
        body: options.body
      })

      console.log('[ElectronFetch] 收到响应:', result.status)

      // 模拟标准的Response对象
      return {
        ok: result.ok,
        status: result.status,
        statusText: result.statusText,
        headers: new Headers(),
        json: async () => JSON.parse(result.data),
        text: async () => result.data,
        blob: async () => new Blob([result.data]),
        arrayBuffer: async () => new TextEncoder().encode(result.data).buffer,
        formData: async () => { throw new Error('FormData not supported') },
        bytes: async () => new Uint8Array(),
        clone: () => { throw new Error('Clone not supported') },
        body: null,
        bodyUsed: false,
        redirected: false,
        type: 'basic',
        url: url
      } as unknown as Response
    } catch (error) {
      console.error('[ElectronFetch] 请求失败:', error)
      throw error
    }
  }

  // 降级到标准fetch
  console.log('[ElectronFetch] 使用标准fetch:', url)
  return fetch(url, options)
}
